package com.rich.dmr.service;

import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.content.Context;
/**
 * JobService to be scheduled by the JobScheduler.
 * start another service
 */
public class DmrUtilService extends JobService {
    private static final String TAG = "DmrUtilService";
    private static SharedPreferences mSp;
    @Override
    public boolean onStartJob(JobParameters params) {
        if (mSp == null) {
            mSp = getApplicationContext().getSharedPreferences("rich_dmr", Context.MODE_PRIVATE);
        }
        boolean shutdown = mSp.getBoolean("shutdown_app",false);
        Log.d("rich----","=================shutdown="+shutdown);
        if(shutdown){
          return true;
        }
        try {
			if(!isServiceRunning()){
				Log.d(TAG, "DmrUtilService not running");
				Intent service = new Intent(getApplicationContext(), DmrService.class);
            	getApplicationContext().startService(service);
			}else{
				Log.d(TAG, "DmrUtilService running");
			}	
        } catch (Exception e) {
            Log.e(TAG, "DmrUtilService not running");
        } finally {
            DmrUtilJob.scheduleJob(getApplicationContext()); // reschedule the job
        }
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }

	private boolean isServiceRunning(){
        ActivityManager mAm = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String mServiceName = DmrService.class.getName();
        for(RunningServiceInfo runningService : 
                mAm.getRunningServices(Integer.MAX_VALUE)){
            if(mServiceName.equals(runningService.service.getClassName())){
                Log.i(TAG, "#####Service is Running");
                return true;
            }
        }
        Log.i(TAG, "#####Service is not Running");
        return false;
    }

}